package com.gegong.imr.client.autoconfig;

import com.gegong.imr.client.IMessageClientProfiles;
import com.gegong.imr.client.config.VBoxWebSrvConfig;
import com.gegong.imr.client.config.VirtualBoxConfig;
import com.gegong.imr.client.exception.EnvironmentException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.telnet.TelnetClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.virtualbox_5_2.IVirtualBox;
import org.virtualbox_5_2.VirtualBoxManager;

import java.io.IOException;

@Slf4j
@Configuration
@Profile(IMessageClientProfiles.VBOX)
public class VBoxAutoConfiguration {


    @Bean
    public VirtualBoxManager virtualBoxManager(VirtualBoxConfig boxConfig, VBoxWebSrvConfig webSrvConfig) {
        VirtualBoxManager virtualBoxManager = VirtualBoxManager.createInstance(null);
        if (vBoxWebSrvAvailable(webSrvConfig))
            virtualBoxManager.connect(webSrvConfig.getUrl(), webSrvConfig.getUsername(), webSrvConfig.getPassword());
        return virtualBoxManager;
    }

    private boolean vBoxWebSrvAvailable(VBoxWebSrvConfig config) {
        TelnetClient telnetClient = new TelnetClient();
        try {
            telnetClient.connect(config.getHost(), config.getPort());
            return telnetClient.isConnected();
        } catch (IOException e) {
            log.error("位于主机{}上的VBox WS尚未启动或端口不正确", config.getHost());
        }
        return false;
    }

}
